import React from "react";
import { Form, Row, Input, Button, Col } from "antd";
import { FormComponentProps } from "antd/lib/form";

import style from "./index.module.scss";
interface FieldItem {
  // 字段label
  label: React.ReactNode;
  // 字段 name
  field: string;
  // 占位消息
  msg?: string;
  // 字段规则
  rules?: Array<any>;
  // 自定义渲染节点
  children?: React.ReactNode;
}
interface IProps extends FormComponentProps {
  fields: Array<FieldItem>;
  onSearch?: (arg: any) => void;
  onReset?: (arg: any) => void;
}

const Search: React.FC<IProps> = ({ form, fields = [], onSearch }) => {
  // 遍历获得所有字段生成 FormItem
  const getFields = () => {
    const count = 6;
    const { getFieldDecorator } = form;
    const children = [];
    for (let field of fields) {
      children.push(
        <React.Fragment key={field.field}>
          <Form.Item label={field.label}>
            {getFieldDecorator(field.field, {
              rules: field.rules
            })(
              field.children ? (
                field.children
              ) : (
                <Input width={180} placeholder={field.msg || "placeholder"} />
              )
            )}
          </Form.Item>
        </React.Fragment>
      );
    }
    return children;
  };
  // 处理点击搜索
  const handleSearch = e => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        onSearch(values);
      }
    });
  };
  // 处理重置表单
  const handleReset = () => {
    form.resetFields();
  };
  return (
    <Form className={style.wrapper} onSubmit={handleSearch} layout="inline">
      <Row className={style.content}>
        {getFields()}
        <Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
          </Button>
        </Form.Item>
      </Row>
    </Form>
  );
};

export default Form.create<IProps>({ name: "ad_search" })(Search);
